package netty.demo04;

import java.net.InetSocketAddress;
import java.util.Scanner;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import netty.demo02.TestEventLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HelloClient
 *
 * @author chenxin
 * @date 2022/05/26 10:09
 **/
public class EventLoopClient {

    private static final Logger log = LoggerFactory.getLogger(EventLoopClient.class);

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup group = new NioEventLoopGroup();

        // 1.启动类
        ChannelFuture channelFuture = new Bootstrap()
            // 2. 添加组件 EventLoop
            .group(group)
            // 3. 选择客户端channel实现
            // 因为服务端接收的是NioSocketChannel
            .channel(NioSocketChannel.class)
            // 4. 添加处理器
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                    // 连接建立后被调用
                    ch.pipeline().addLast(new StringEncoder());
                }
            })
            // 5. 连接到服务器
            .connect(new InetSocketAddress("localhost", 8080));

        // 使用sync()方法同步接收结果
        Channel channel = channelFuture.sync().channel();

        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String line = scanner.nextLine();

                if (line.equals("q")) {
                    channel.close();
                    break;
                }

                channel.writeAndFlush(line);
            }
        }, "input").start();

        // 关闭处理
        ChannelFuture closeFuture = channel.closeFuture();

        // 同步
        // closeFuture.sync();
        // log.info("关闭之后的处理");

        // 异步
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.info("关闭之后的处理");
                // 优雅的停止所有nio线程
                group.shutdownGracefully();
            }
        });

    }

}